package ort.persistence;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import ort.domain.Fight;
import ort.domain.JudgeCard;
import ort.domain.TableJudge;

import com.hazelcast.client.ClientConfig;
import com.hazelcast.client.HazelcastClient;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;

public class ServerClient {

	private HazelcastInstance client;
	private static ServerClient instance = null;
	
	public static ServerClient getInstance(){
		if (instance == null) {
			instance = new ServerClient();
		}
		return instance;
	}

	private ServerClient() {

		try {
			// Obtengo un cliente para el servidor
			getClientServerConfig();

		} catch (Exception e) {
			// No se encontro un servidor levantado por lo cual lo levanto.
			new BoxServer().run();

			// Obtengo nuevamente el cliente luego de levantado el server
			getClientServerConfig();
		}

	}

	/**
	 * Metodo encargado de setear un cliente para que consuma la informacion del
	 * servidor de Jueces
	 */
	public void getClientServerConfig() {

		// TODO: localhost se debe parametrizar en un archivo de propiedades

		ClientConfig clientConfig = new ClientConfig();
		clientConfig.addAddress("localhost:5701");
		client = HazelcastClient.newHazelcastClient(clientConfig);

	}

	public void saveFight(Fight fight) {

		IMap map = client.getMap("fight");
		map.put("fight", fight);

	}
	
	public Fight getFigth() {

		IMap map = client.getMap("fight");
		return (Fight)map.get("fight");

	}
	
	public Integer getNextJudgeId() {
		
		int qtJudges = client.getMap("judgeMap").size();
		if (qtJudges == 3) {
			return null;
		}
		return  ++qtJudges;
	}

	public void saveJudge(TableJudge tableJudge) {

		IMap map = client.getMap("judgeMap");
		map.put(new Integer(tableJudge.getId()), tableJudge);

	}

	public TableJudge getJudge(int judgeId) {

		IMap map = client.getMap("judgeMap");
		return (TableJudge)map.get(new Integer(judgeId));

	}
	
	public boolean hasAllJudgeCards() {

		IMap map = client.getMap("judgeMap");
		Set<Integer> keys = map.keySet();
		boolean all = true;
		
		// Valido que hayan 3 jueces
		if (keys.size() < 3) {
			return false;
		}
		
		for (Integer key : keys) {
			all &= ((TableJudge)map.get(key)).getCard().getRoundsScore().size() > 0;
		}
		return all;

	}
	
	public List<JudgeCard> getJudgesCards() {

		IMap map = client.getMap("judgeMap");
		Set<Integer> keys = map.keySet();
		boolean all = true;
		List<JudgeCard> judgeCards = new ArrayList<JudgeCard>(); 
		
		for (Integer key : keys) {
			judgeCards.add(((TableJudge)map.get(key)).getCard());
		}
		return judgeCards;

	}

}